﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace App
{
    public partial class frmLogin : Form
    {
        private BackgroundWorker m_bw;
        public frmLogin()
        {
            InitializeComponent();
            this.Text = Properties.Settings.Default.Title;
            Entities db = new Entities();
            txt1.DataSource = db.T_Stuff.ToList();
            txt1.DisplayMember = "name";
            txt1.ValueMember = "stID";
            InitBW();
        }

        private void InitBW()
        {
            m_bw = new BackgroundWorker();
            m_bw.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                string str = e.Argument.ToString();
                string[] ss = str.Split('-');
                e.Result = Login(ss[0], ss[1]);
            };
            m_bw.RunWorkerCompleted += delegate(object s2, RunWorkerCompletedEventArgs e2)
            {
                lbInfo.Text = "";
                btnGo.Enabled = true;
                btnCancel.Enabled = true;
                if ((bool)e2.Result == true)
                {
                    Close();
                    Startup.GetApp().Show();
                }
                else
                {
                    Msg.ShowError("用户名或者密码错误，请检查核对。");
                }
            };
        }

      

        private bool Login(string username,string password)
        {
            bool isLogin = false;

            Entities db = new Entities();
            
            //
            try
            {
                var user = db.T_Stuff.Where(a => a.name == username && a.password == password);
                foreach (var u in user)
                {
                    if (u.roleID == 21)
                    {
                        isLogin = true;
                        Startup.GetApp().CurrentUser = u;
                    }
                    //
                    break;
                }
            }
            catch
            {
                Msg.ShowError("服务器连接失败，请检查网络情况！");
            }
            return isLogin;
        }

        private void txt1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (sender == txt1)
                {
                    txt2.Focus();
                }
                else
                {
                    btnGo_Click(sender, e);
                }
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            btnGo.Enabled = false;
            btnCancel.Enabled = false;
            lbInfo.Text = "正在登录... ";
            m_bw.RunWorkerAsync(txt1.Text + "-" + txt2.Text);
        }

        private void btn3_Click(object sender, EventArgs e)
        {
            Startup.GetApp().Close();
        }


    }
}
